package com.zjdiepu.www.hzicbc.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.diepu.www.client.hzicbc.proxy.enums.FileListType;
import com.diepu.www.client.hzicbc.proxy.enums.PicIdType;
import com.diepu.www.client.hzicbc.proxy.request.PublicRequest;
import com.diepu.www.client.hzicbc.proxy.response.HzicbcBaseResponse;
import com.diepu.www.client.hzicbc.proxy.response.PublicResponse;
import com.diepu.www.client.partner.proxy.request.OpenCardbackReasonRequest;
import com.diepu.www.client.proxy.hzicbc.request.ApplyBackInfo;
import com.diepu.www.client.proxy.hzicbc.request.ApplyBackRequest;
import com.diepu.www.client.proxy.hzicbc.request.BackNoticeInfo;
import com.diepu.www.client.proxy.hzicbc.request.BackNoticeRequest;
import com.diepu.www.client.proxy.hzicbc.request.CommonRequest;
import com.diepu.www.client.proxy.hzicbc.request.CreditResultRequest;
import com.diepu.www.client.proxy.hzicbc.request.FileListNoticeInfo;
import com.diepu.www.client.proxy.hzicbc.request.FileListNoticeRequest;
import com.diepu.www.client.proxy.hzicbc.request.HandPicInfo;
import com.diepu.www.client.proxy.hzicbc.request.HandPicRequest;
import com.diepu.www.client.proxy.hzicbc.response.handPic.HandPicResponse;
import com.icbc.api.core.ApiClient;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.OpenCardStatus;
import com.zjdiepu.www.base.enums.type.TypeData;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.consts.ProxyService;
import com.zjdiepu.www.hzicbc.biz.IHzicbcProxyService;
import com.zjdiepu.www.proxy.biz.own.HzBiz;
import com.zjdiepu.www.proxy.biz.own.HzGhBiz;
import com.zjdiepu.www.proxy.biz.transfer.ITransferDzApplyDiviService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferOtherAttachmentsService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwInterviewInfoService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwOpenCardHzicbcService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwOrdernoBankService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferZxQueryCreditApplyService;
import com.zjdiepu.www.proxy.model.dto.own.SysUserProxy;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOrdernoBank;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferZxQueryCreditApply;
import com.zjdiepu.www.security.exception.BasePartnerException;
import com.zjdiepu.www.security.server.convert.MyJson;
import com.zjdiepu.www.security.server.core.Partners;
import com.zjdiepu.www.security.server.interceptor.PartnerProvider;
import com.zjdiepu.www.service.base.ICommonLogService;
import com.zjdiepu.www.service.hzicbc.IHzicbcService;
import com.zjdiepu.www.service.partner.IDiepuService;
import com.zjdiepu.www.service.partner.IcbcApiService;

/**
 * 类描述:杭州工商银行接口<br/> 
 * 项目名称:diepu-parent-partner <br/> 
 * 类名称:XinHeHuiController <br/>     
 * 创建人:xiongxiaotun <br/> 
 * 创建时间:2017年8月15日 下午5:56:32  <br/>   
 * 修改人:xiongxiaotun <br/> 
 * 修改时间: 2017年8月15日 下午5:56:32   <br/>  
 * 修改备注:   <br/> 
 * @version V1.0   <br/>
 */
@MyJson
@RestController
@RequestMapping(value="HzicbcController", produces = "application/json;charset=UTF-8", consumes="application/x-www-form-urlencoded;charset=UTF-8", method = RequestMethod.POST)
@Api(tags = { "杭州工商银行接口" }, produces = "application/json;charset=UTF-8", consumes="application/x-www-form-urlencoded;charset=UTF-8")
@PartnerProvider(partner = Partners.HZ_ICBC)
public class HzicbcController {
	private Logger logger = LoggerFactory.getLogger(HzicbcController.class);
	
	@Autowired
	private HzBiz hzBiz;
	
	@Autowired
	private ApiClient hzicbcApiClient;
	
	@Resource
	private IHzicbcService hzicbcService;
	
	@Autowired
	private IDiepuService diepuService;
	
	@Autowired
	private ITransferDzApplyDiviService transferDzApplyDiviService;
	
	@Resource
	private ITransferYwOpenCardHzicbcService transferYwOpenCardHzicbcService;
	
	@Resource
	private IcbcApiService icbcApiService;
	
	@Resource
	private IHzicbcProxyService hzicbcProxyService;
	
	@Resource
	private HzGhBiz hzGhBiz;
	
	@Resource
	private ICommonLogService commonLogService;
	
	@Resource
	private ITransferZxQueryCreditApplyService transferZxQueryCreditApplyService;
	
	@Resource
	private ITransferOtherAttachmentsService transferOtherAttachmentsService;
	@Resource
	private ITransferYwOrdernoBankService transferYwOrdernoBankService;
	@Resource
	private ITransferYwInterviewInfoService transferYwInterviewInfoService;
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: multimediaBack <br/>
	 * @Description: 多媒体资料退回接口 <br/>
	 * @param commonRequest
	 * @return
	 * @version V1.0 <br/>
	 * @throws BasePartnerException 
	 */
	@ApiOperation(value = "多媒体资料退回接口", response = HzicbcBaseResponse.class, httpMethod = "POST")
	@RequestMapping("multimediaBack")
	public HzicbcBaseResponse multimediaBack(CommonRequest commonRequest) {
		HzicbcBaseResponse response = new HzicbcBaseResponse();
		boolean statusEvent = false;
		String exceptionDes = null;
		try {
			String reqparam = commonRequest.getReqparam();
			if(StringUtils.isBlank(reqparam)) {
				exceptionDes = "回调参数为空";
				logger.error("HzicbcController.multimediaBack params is empty.");
				response.setPub(PublicResponse.failParam());
				exceptionDes = "多媒体资料退回接口参数为空";
				return response;
			}
			ApplyBackRequest applyBackRequest = JSON.parseObject(reqparam, ApplyBackRequest.class);
			
			PublicRequest pub = applyBackRequest.getPub();
			String orderno = pub.getOrderno();
			if(StringUtils.isBlank(orderno)) {
				exceptionDes = "参数银行订单号为空";
				logger.error("HzicbcController.multimediaBack param orderno is empty.");
				response.setPub(PublicResponse.failParam());
				return response;
			}
			statusEvent = true;
			String backnote = Optional.ofNullable(applyBackRequest).map(item -> item.getReq()).map(item -> item.getBacknote()).orElse(null);
			return hzicbcProxyService.saveMultimediaBack(orderno, backnote);
		} catch(Exception e){
			Throwable throwable = e.getCause();
			exceptionDes = throwable != null ? throwable.toString() : "未知错误";
			throw e;
		} finally {
			commonLogService.insertCallbackLog(commonRequest, response, exceptionDes, ProxyService.MULTIMEDIA_BACK, statusEvent);
		}
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: handPic <br/>
	 * @Description:手工获取图片接口 <br/>
	 * @param commonRequest
	 * @return
	 * @version V1.0 <br/>
	 * @throws BasePartnerException 
	 */
	@ApiOperation(value = "手工获取图片接口", response = HzicbcBaseResponse.class, httpMethod = "POST")
	@RequestMapping("handPic")
	public HandPicResponse handPic(CommonRequest commonRequest) {
		HandPicResponse response = new HandPicResponse();
		boolean statusEvent = false;
		String exceptionDes = null;
		try {
			String reqparam = commonRequest.getReqparam();
			if(StringUtils.isBlank(reqparam)) {
				logger.error("HzicbcController.handPic params is empty.");
				response.setPub(PublicResponse.failParam());
				exceptionDes = "工商银行手工获取图片接口参数为空";
				return response;
			}
			HandPicRequest handPicRequest = JSON.parseObject(reqparam, HandPicRequest.class);
			
			PublicRequest pub = handPicRequest.getPub();
			String orderno = pub.getOrderno();
			if(StringUtils.isBlank(orderno)) {
				logger.error("HzicbcController.handPic param orderno is empty.");
				response.setPub(PublicResponse.failParam());
				return response;
			}
			HandPicInfo req = handPicRequest.getReq();
			String picid = req.getPicid();
			PicIdType picIdType = PicIdType.getByCode(picid);
			if(null == picIdType) {
				logger.error("HzicbcController.handPic param picid is error.");
				response.setPub(PublicResponse.failParam());
				return response;
			}
			response = hzicbcProxyService.handPic(orderno, picIdType);
			statusEvent = true;
			return response;
		} catch(Exception e){
			Throwable throwable = e.getCause();
			exceptionDes = throwable != null ? throwable.toString() : "未知错误";
			throw e;
		} finally {
			commonLogService.insertCallbackLog(commonRequest, response, exceptionDes, ProxyService.HAND_PIC, statusEvent);
		}
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: applyBack <br/>
	 * @Description: 申请分期退回接口 <br/>
	 * @param creditResultRequest
	 * @return
	 * @version V1.0 <br/>
	 * @throws BasePartnerException 
	 */
	@ApiOperation(value = "申请分期退回接口", response = HzicbcBaseResponse.class, httpMethod = "POST")
	@RequestMapping("applyDiviBack")
	public HzicbcBaseResponse applyDiviBack(CommonRequest commonRequest) {
		HzicbcBaseResponse response = new HzicbcBaseResponse();
		boolean statusEvent = false;
		String exceptionDes = null;
		try {
			String reqparam = commonRequest.getReqparam();
			if(StringUtils.isBlank(reqparam)) {
				logger.error("HzicbcController.applyDiviBack params is empty.");
				response.setPub(PublicResponse.failParam());
				exceptionDes = "工商银行申请分期退回接口参数为空";
				return response;
			}
			ApplyBackRequest applyBackRequest = JSON.parseObject(reqparam, ApplyBackRequest.class);
			
			PublicRequest pub = applyBackRequest.getPub();
			String orderno = pub.getOrderno();
			if(StringUtils.isBlank(orderno)) {
				logger.error("HzicbcController.applyDiviBack param orderno is empty.");
				response.setPub(PublicResponse.failParam());
				return response;
			}
			ApplyBackInfo req = applyBackRequest.getReq();
			String backnote = req.getBacknote();
			response = hzicbcProxyService.saveApplyDiviBack(orderno, backnote, true);
			statusEvent = true;
			return response;
		} catch(Exception e){
			Throwable throwable = e.getCause();
			exceptionDes = throwable != null ? throwable.toString() : "未知错误";
			throw e;
		} finally {
			commonLogService.insertCallbackLog(commonRequest, response, exceptionDes, ProxyService.APPLY_DIVI_BACK, statusEvent);
		}
	}
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: fileListNotice <br/>
	 * @Description: 文件清单生成通知接口 <br/>
	 * @param fileListNoticeRequest
	 * @return
	 * @version V1.0 <br/>
	 */
	@ApiOperation(value = "文件清单生成通知接口", response = HzicbcBaseResponse.class, httpMethod = "POST")
	@RequestMapping("fileListNotice")
	public HzicbcBaseResponse fileListNotice(CommonRequest commonRequest) {
		HzicbcBaseResponse response = new HzicbcBaseResponse();
		boolean statusEvent = false;
		String exceptionDes = null;
		try {
			String reqparam = commonRequest.getReqparam();
			if(StringUtils.isBlank(reqparam)) {
				logger.error("HzicbcController.fileListNotice params is empty.");
				response.setPub(PublicResponse.failParam());
				exceptionDes = "工商银行文件清单生成通知接口参数为空";
				return response;
			}
			FileListNoticeRequest fileListNoticeRequest = JSON.parseObject(reqparam, FileListNoticeRequest.class);
			
			FileListNoticeInfo req = fileListNoticeRequest.getReq();
			FileListType byCode = FileListType.getByCode(req.getFiletype());
			if(byCode == FileListType.FILE_KKQDWJ) {
				String filePath = hzicbcProxyService.saveFileDownload(FileListType.getByCode(req.getFiletype()), req.getFilesrc(), req.getDatadt());
				if(StringUtils.isNotBlank(filePath)) {
					// 解析文档 
					transferYwOpenCardHzicbcService.updateYwOpenCardicbc(filePath);
					response.setPub(PublicResponse.success());
					statusEvent = true;
					return response;
				}
				response.setPub(PublicResponse.failBusi());
				return response;
			} else { //其它清单
				response.setPub(PublicResponse.success());
				statusEvent = true;
				return response;
			}
		} catch(Exception e){
			Throwable throwable = e.getCause();
			exceptionDes = throwable != null ? throwable.toString() : "未知错误";
			throw e;
		} finally {
			commonLogService.insertCallbackLog(commonRequest, response, exceptionDes, ProxyService.FILE_LIST_NOTICE, statusEvent);
		}
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: backNotice <br/>
	 * @Description: 专项卡申请退回接口 <br/>
	 * @param backNoticeRequest
	 * @return
	 * @version V1.0 <br/>
	 */
	@ApiOperation(value = "专项卡申请退回接口", response = HzicbcBaseResponse.class, httpMethod = "POST")
	@RequestMapping("backNotice")
	public HzicbcBaseResponse backNotice(CommonRequest commonRequest) {
		HzicbcBaseResponse response = new HzicbcBaseResponse();
		boolean statusEvent = false;
		String exceptionDes = null;
		try {
			String reqparam = commonRequest.getReqparam();
			if(StringUtils.isBlank(reqparam)) {
				logger.error("HzicbcController.backNotice params is empty.");
				response.setPub(PublicResponse.failParam());
				exceptionDes = "工商银行专项卡申请退回接口参数为空";
				return response;
			}
			BackNoticeRequest backNoticeRequest = JSON.parseObject(reqparam, BackNoticeRequest.class);
			try {
				String orderno = null;
				String backnote=null;
				if(null != backNoticeRequest) {
					PublicRequest pub = backNoticeRequest.getPub();
					if(null != pub) {
						orderno = pub.getOrderno();
					}
					BackNoticeInfo req=backNoticeRequest.getReq();
					if(null != req){
						backnote=req.getBacknote();
					}
				}
				OpenCardbackReasonRequest openCardBack=new OpenCardbackReasonRequest();
				openCardBack.setBacknote(backnote);
				openCardBack.setOpenCardStatus(OpenCardStatus.YU_SHOU_LI_TUI_HUI.getCode());
				TransferYwOrdernoBank transferYwOrdernoBank= transferYwOrdernoBankService.getByOrderNo(orderno);
				if(transferYwOrdernoBank==null){
					logger.error("HzicbcController.backNotice happend customer exception. errorCode is {}, errorMsg is {}.", "999", "业务ID不存在 ");
					response.setPub(PublicResponse.success());
					return response;
				}
				openCardBack.setBusiId(transferYwOrdernoBank.getBusiId());
				boolean flag = diepuService.openCardBackReason(openCardBack);
				if(flag){
					response.setPub(PublicResponse.success());
					statusEvent = true;
				} else {
					response.setPub(PublicResponse.failBusi());
				}
			} catch (BasePartnerException e) {
				logger.error("HzicbcController.backNotice happend customer exception. errorCode is {}, errorMsg is {}.", e.getErrorCode(), e.getErrorMsg());
				response.setPub(PublicResponse.failParam());
			} catch(Exception e) {
				logger.error("HzicbcController.backNotice happend exception. exception stack is : ", e);
				response.setPub(PublicResponse.failError());
			}
			return response;
		} catch(Exception e){
			Throwable throwable = e.getCause();
			exceptionDes = throwable != null ? throwable.toString() : "未知错误";
			throw e;
		} finally {
			commonLogService.insertCallbackLog(commonRequest, response, exceptionDes, ProxyService.BACK_NOTICE, statusEvent);
		}
	}
	
	
	
	/**
	 * 征信结果返回接口
	 * @param creditResultRequest
	 * @return
	 */
	@RequestMapping(value="creditResult")
	public HzicbcBaseResponse creditResult(CommonRequest commonRequest) {
		HzicbcBaseResponse response = new HzicbcBaseResponse();
		boolean statusEvent = false;
		String exceptionDes = null;
		try {
			String reqparam = commonRequest.getReqparam();
			if(StringUtils.isBlank(reqparam)) {
				logger.error("HzicbcController.creditResult params is empty.");
				response.setPub(PublicResponse.failParam());
				exceptionDes = "工商银行征信结果返回接口接口参数为空";
				return response;
			}
			String orderno = "";
			CreditResultRequest creditResultRequest = null;
			try {
				creditResultRequest = JSON.parseObject(reqparam, CreditResultRequest.class);
				//银行的唯一单号
				orderno = creditResultRequest.getPub().getOrderno();
				if(StringUtils.isBlank(orderno)) {
					response.setPub(PublicResponse.failBusi());
					return response;
				}
				TransferZxQueryCreditApply transferZxQueryCreditApply = new TransferZxQueryCreditApply();
				transferZxQueryCreditApply.setBankOrderNo(orderno);
				transferZxQueryCreditApply.setDpStatus(DpStatus.NORMAL.getCode());
				transferZxQueryCreditApply.setTypeData(TypeData.HZICBC.getCode());
				transferZxQueryCreditApply.setOrderSql(" `CREATED` DESC ");// 取最新的 ,pan，3.26
				transferZxQueryCreditApply = transferZxQueryCreditApplyService.selectRefined(transferZxQueryCreditApply);
				//银行订单号没有找到申请记录
				if(null == transferZxQueryCreditApply) {
					response.setPub(PublicResponse.success());
					statusEvent = true;
					exceptionDes = "银行订单号没有找到本地申请记录，返回成功结果，结束该订单";
					return response;
				}
				
				creditResultRequest.creditApply = creditResultRequest.newCreditApply();
				creditResultRequest.creditApply.setQueryCreditApplyId(transferZxQueryCreditApply.getId());
				creditResultRequest.creditApplies.add(creditResultRequest.creditApply);
	
				boolean creditResult = icbcApiService.creditResult(creditResultRequest);
				if(!creditResult) {
					response.setPub(PublicResponse.failBusi());
					exceptionDes = "请求主程序失败，返回业务错误给工商银行";
					return response;
				}
				
				SysUserProxy sysUserProxy = new SysUserProxy();
				sysUserProxy.setUserId(SystemConsts.DEFAULT_ID);
				sysUserProxy.setLoginName("工行查询");
				int count = hzGhBiz.diepuZxFeedbackHandle(sysUserProxy, creditResultRequest.getReq().getResult(),orderno,creditResultRequest);
				if(count < 1 && count == 0) {
					response.setPub(PublicResponse.failBusi());
					exceptionDes = "请求主程序成功，更新本地记录失败，返回业务错误给工商银行";
					return response;
				}
				
				if(creditResult && count > 0) {
					response.setPub(PublicResponse.success()); 
					statusEvent = true;
					return response;
				}
			} catch (BasePartnerException e) { //这里的的异常不要记录日记到回调中，这时调用主程序的错误，如有需要，请记录到调用主程序的日记中
				response.setPub(PublicResponse.failError()); 
				return response;
			} catch (Exception e) {
				response.setPub(PublicResponse.failError()); 
				return response;
			}
			response.setPub(PublicResponse.failError()); 
			return response;
		}  catch(Exception e){
			Throwable throwable = e.getCause();
			exceptionDes = throwable != null ? throwable.toString() : "未知错误";
			throw e;
		} finally {
			commonLogService.insertCallbackLog(commonRequest, response, exceptionDes, ProxyService.APPLY_CREDIT, statusEvent);
		}
	}
}
